package com.tdam2011.grupo05.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.control.app.TdamApplication;
import com.tdam2011.grupo05.services.MessageService;
import com.tdam2011.grupo05.services.ServiceHelper;
import com.tdam2011.grupo05.services.constant.ServiceActions;
import com.tdam2011.grupo05.ui.activities.config.account.AccountActivity;
import com.tdam2011.grupo05.utils.preference.PreferencesHelper;

public class InicioActivity extends Activity {

	private static final int REQUEST_CODE_LOGIN = 2;
	private final static String TAG = "InicioActivity";
	private final static int REQUEST_CODE_ACCOUNT = 1;

	private PreferencesHelper mHelper;

	private ProgressBar mProgressBar;
	private TextView mTextView;
	private Handler mHandler = new Handler();
	private ServiceHelper mServiceHelper;
	private String username;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inicio);

		mTextView = (TextView) findViewById(R.id.txt_inicio);
		mProgressBar = (ProgressBar) findViewById(R.id.inicio_progress_bar);
		mProgressBar.setVisibility(View.INVISIBLE);
		mServiceHelper = ServiceHelper.getIntance(this);

		mHelper = ((TdamApplication) getApplication()).getPreference();
		final Intent service = new Intent(this, MessageService.class);
		service.setAction(ServiceActions.START_SERVICE);
		startService(service);
	}

	@Override
	protected void onStart() {
		super.onStart();

	}

	@Override
	protected void onResume() {
		Log.d(TAG, "onResume");
		super.onResume();

		boolean config = mHelper.getInitialConfigState();
		boolean accountReady = mHelper.getAccountConfigStatus();

		if (config) {
			if (accountReady) {
				Log.d(TAG,
						"account="
								+ ((TdamApplication) getApplication())
										.getCurrentAccount());
				load(true);
			} else {
				final Intent login = new Intent(this, LoginActivity.class);
				login.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				startActivityForResult(login, REQUEST_CODE_LOGIN);
			}

		} else if (!mHelper.getAccountConfigStatus()) {
			Intent intent = new Intent(this, AccountActivity.class);
			startActivityForResult(intent, REQUEST_CODE_ACCOUNT);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_ACCOUNT) {
			mHelper.setInitialConfigState(true);
			if (resultCode == Activity.RESULT_OK) {
				mHelper.saveUsername(data.getExtras().getString(
						PreferencesHelper.KEY_USERNAME));
				mHelper.savePassword(data.getExtras().getString(
						PreferencesHelper.KEY_PASSWORD));
				mHelper.saveAccountConfigStatus(true);
				mHelper.setSyncState(true);
				load(true);

			} else if (resultCode == Activity.RESULT_CANCELED) {
				mHelper.saveAccountConfigStatus(false);
				mHelper.setSyncState(false);
				load(false);
			}
		} else if (requestCode == REQUEST_CODE_LOGIN) {
			if (resultCode == Activity.RESULT_OK) {
				mHelper.saveAccountConfigStatus(true);
				mHelper.saveUsername((((TdamApplication) getApplication())
						.getCurrentAccount().getUsername()));
				mHelper.savePassword((((TdamApplication) getApplication())
						.getCurrentAccount().getPassword()));
				mHelper.updateLastSync((((TdamApplication) getApplication())
						.getCurrentAccount().getLastSync()));
				mHelper.setSyncState(true);
				load(true);

			} else if (resultCode == Activity.RESULT_CANCELED) {
				mHelper.saveAccountConfigStatus(false);
				mHelper.setSyncState(false);
				load(false);
			} else {
				Log.d(TAG, "no resultCode");
				finish();
			}
		} else {
			return;
		}
	}

	public void load(boolean loadService) {
		if (loadService) {
			final Intent service = new Intent(this, MessageService.class);
			service.setAction(ServiceActions.START_SERVICE_MESSAGE_ACTION);
			startService(service);
		}
		if (((TdamApplication) getApplication()).getCurrentAccount() == null) {
			((TdamApplication) getApplication())
					.updateCurrentAccount(mServiceHelper.getDataManager().get(
							mHelper.getUsername(), mHelper.getPassword()));
		}
		username = mHelper.getUsername();
		mProgressBar.setVisibility(View.VISIBLE);
		mProgressBar.setIndeterminate(true);
		Runnable runn = new Runnable() {
			int progress = 0;

			@Override
			public void run() {

				while (progress < 100) {
					progress++;
					if (progress == 50) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								String value = mTextView.getText().toString();
								if (username
										.equals(PreferencesHelper.DEFAULT_VALUE)) {
									mTextView.setText(getResources().getString(
											R.string.dialog_start_activity));
								} else {
									mTextView
											.setText(value
													+ getResources()
															.getString(
																	R.string.dialog_start_activity_account)
													+ username);
								}
							}
						});
					}
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				gotoDashboard();
			}
		};

		new Thread(runn).start();

	}

	public void gotoLogin() {
		Intent login = new Intent(this, LoginActivity.class);
		startActivity(login);
	}

	public void gotoDashboard() {
		Log.d(TAG, "go to dashboard");

		Intent dashBoard = new Intent(this, DashboardActivity.class);
		dashBoard.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		dashBoard.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		dashBoard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		dashBoard.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		startActivity(dashBoard);
		finish();
	}

	public void logout() {
		Log.i(TAG, "logout() ");
		finish();
	}

}
